<template>
  <el-dialog :title="title" :visible="showDialog" width="400px" @close ="btnCancel">
    <el-form ref="addSubRef" :model="subForm" :rules="rules">
      <el-form-item prop="subjectName" label="学科名称" label-width="80px">
        <el-input v-model="subForm.subjectName" />
      </el-form-item>
      <el-form-item prop="isFrontDisplay" label="是否显示">
        <el-switch
          v-model="subForm.isFrontDisplay"
          active-color="#13ce66"
          inactive-color="#ff4949"
          active-value="1"
          inactive-value="0"
        >
        </el-switch>
      </el-form-item>
    </el-form>
    <el-row slot="footer">
      <el-col>
        <el-button size="small" @click="btnCancel">取消</el-button>
        <el-button size="small" type="primary" @click="btnOK">确定</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { addSub, getSub, editSub } from '../../api/hmmm/subjects'
export default {
  name: 'SubAdd',
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      subForm: {
        subjectName: '', // 学科名称
        isFrontDisplay: '1'
      },
      rules: {
        subjectName: [
          { required: true, message: '请输入学科名称', trigger: 'blur' }
        ]
      }

    }
  },
  computed: {
    title () {
      return this.subForm.id ? '修改学科' : '新增学科'
    }
  },
  methods: {
    // 数据回显
    async getSub (id) {
      const { data } = await getSub(id)
      this.subForm = data
      // 把数字换成字符串 切换状态
      this.subForm.isFrontDisplay = (data.isFrontDisplay).toString()
    },

    // 点击确定
    async btnOK () {
      try {
        this.$refs.addSubRef.validate()
        if (this.subForm.id) {
          // 有id 编辑
          await editSub(this.subForm)
          this.$message.success('修改成功')
        } else {
          // 无id 新增
          await addSub(this.subForm)
        }
        this.$emit('getSubList')
        this.$emit('update:showDialog', false)
        this.$message.success('操作成功')
      } catch (error) {
        console.log(error)
      }
    },
    // 点击取消
    btnCancel () {
      //
      this.subForm = {
        subjectName: '', // 学科名称
        isFrontDisplay: '1'
      }
      // 移除校验
      this.$refs.addSubRef.resetFields()
      this.$emit('update:showDialog', false)
    }
  }
}
</script>

<style scoped></style>
